package com.tus;

import com.tus.handler.DownloadHandler;
import com.tus.handler.FileHandler;
import com.tus.handler.UploadHandler;
import com.tus.storage.LocalFileStorage;
import com.tus.storage.FileStorage;
import com.tus.store.SQLiteMetadataStore;
import com.tus.task.ExpiredUploadCleaner;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.codec.http.cors.CorsHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;


@Slf4j
public class TusNettyServer {
    private final int port;
    private final String uploadPathPrefix;
    private final String downloadPathPrefix;

    public TusNettyServer(int port, String uploadPathPrefix, String downloadPathPrefix) {
        this.port = port;
        this.uploadPathPrefix = uploadPathPrefix;
        this.downloadPathPrefix = downloadPathPrefix;
    }

    public void start() throws Exception {
        SQLiteMetadataStore metadataStore = new SQLiteMetadataStore("./db/uploads.db");
        FileStorage fileStorage = new LocalFileStorage("./uploads");
        ExpiredUploadCleaner cleaner = new ExpiredUploadCleaner(metadataStore, fileStorage);
        // 启动清理任务
        cleaner.start();

        int core = Runtime.getRuntime().availableProcessors();
        EventLoopGroup bossGroup = new NioEventLoopGroup(core);
        EventLoopGroup workerGroup = new NioEventLoopGroup(core * 2);

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    CorsConfig cors = CorsConfigBuilder.forAnyOrigin().allowedRequestHeaders("Origin", "X-Requested-With", "Content-Type", "Upload-Length", "Upload-Offset", "Tus-Resumable", "Upload-Metadata", "Upload-Checksum", "Upload-Concat").exposeHeaders("Location", "Tus-Resumable", "Upload-Length", "Upload-Offset", "Upload-Metadata", "Accept-Ranges", "Content-Range", "Content-Length", "Content-Disposition").allowedRequestMethods(HttpMethod.POST, HttpMethod.GET, HttpMethod.HEAD, HttpMethod.PATCH, HttpMethod.DELETE, HttpMethod.OPTIONS).allowCredentials().build();

                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpServerCodec());
                    p.addLast(new HttpObjectAggregator(50 * 1024 * 1024)); // 50MB
                    p.addLast(new ChunkedWriteHandler());
                    p.addLast(new CorsHandler(cors));
                    p.addLast(new FileHandler(Arrays.asList(new UploadHandler(metadataStore, fileStorage, uploadPathPrefix), new DownloadHandler(metadataStore, fileStorage, downloadPathPrefix))));
                }
            });

            ChannelFuture f = b.bind(port).sync();
            log.info("Tus Server started on 0.0.0.0:{}", port);
            log.info("Tus upload Endpoint: on 0.0.0.0:{}{}", port, uploadPathPrefix);
            log.info("Tus download Endpoint: on 0.0.0.0:{}{}", port, downloadPathPrefix);
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            cleaner.shutdown();
        }
    }

    public static void main(String[] args) throws Exception {
        new TusNettyServer(8080, "/uploads", "/download").start();
    }
}
